package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.entity.Course;
import com.xmy.cultivate.entity.Grade;
import com.xmy.cultivate.entity.StudentGrade;
import com.xmy.cultivate.entity.TrackDetail;
import com.xmy.cultivate.entity.TrackMarket;
import com.xmy.cultivate.mapper.TrackMarketMapper;
import com.xmy.cultivate.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TrackMarketServiceImpl extends ServiceImpl<TrackMarketMapper, TrackMarket> implements ITrackMarketService {
    @Autowired
    @Lazy
    private ITrackDetailService nITrackDetailService;

    @Autowired
    @Lazy
    private IGradeService nIGradeService;

    @Autowired
    @Lazy
    private ICourseService iCourseService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Lazy
    private IStudentGradeService iStudentGradeService;

    @Transactional
    public TrackDetail addBatchSourse(TrackDetail trackDetail) {
        int type = 1;
        TrackMarket trackMarketInfo = this.getById(trackDetail.getId());
        String[] sourseIdStr = trackDetail.getSourseIdList().split(",");
        //条件判断
        String[] schoolIdStr = null;
        if (trackDetail.getSchoolIdStr() != null && !trackDetail.getSchoolIdStr().isEmpty()) {
            schoolIdStr = trackDetail.getSchoolIdStr().split(",");
        }
        String[] yearClassIdStr = null;
        if (trackDetail.getYearClassIdStr() != null && !trackDetail.getYearClassIdStr().isEmpty()) {
            yearClassIdStr = trackDetail.getYearClassIdStr().split(",");
        } else {
            // 获取战队的年级
            TrackMarket trackMarket = this.getById(trackDetail.getId());
            if (trackMarket.getYearClassId() != null) {
                yearClassIdStr = new String[]{String.valueOf(trackMarket.getYearClassId())};
                trackDetail.setYearClassIdStr(String.valueOf(trackMarket.getYearClassId()));
            }
        }
        String[] classTypeIdStr = null;
        if (trackDetail.getClassTypeIdStr() != null && !trackDetail.getClassTypeIdStr().isEmpty()) {
            classTypeIdStr = trackDetail.getClassTypeIdStr().split(",");
        }
        String[] gradeIdStr = null;
        if (trackDetail.getGradeIdStr() != null && !trackDetail.getGradeIdStr().isEmpty()) {
            gradeIdStr = trackDetail.getGradeIdStr().split(",");
        }
        TrackDetail trackDetailReturn = new TrackDetail();
        for (String string : sourseIdStr) {
            Long sourseId = Long.valueOf(string);
            QueryWrapper<TrackDetail> trackDetailQueryWrapper = new QueryWrapper<>();
//            trackDetailQueryWrapper.eq("track_id",trackDetail.getId());
            trackDetailQueryWrapper.eq("track_detail.sourse_id", sourseId);
            trackDetailQueryWrapper.eq("track_detail.deleted", 0);
            trackDetailQueryWrapper.eq("track_market.deleted", 0);
            trackDetailQueryWrapper.eq("track_detail.type", type);
            trackDetailQueryWrapper.eq("track_market.year_part", trackMarketInfo.getYearPart());
            trackDetailQueryWrapper.eq("track_market.quarter_num", trackMarketInfo.getQuarterNum());
            trackDetailQueryWrapper.eq("track_detail.classify", trackMarketInfo.getClassify());
            trackDetailQueryWrapper.eq("track_detail.track_type", trackMarketInfo.getTrackType());
            if (schoolIdStr != null && schoolIdStr.length > 0) {
                String[] finalSchoolIdStr = schoolIdStr;
                trackDetailQueryWrapper.and(q -> {
                    q.eq("track_detail.school_id_str", "").or().isNull("track_detail.school_id_str");
                    StringBuilder schoolSql = new StringBuilder();
                    for (String s : finalSchoolIdStr) {
                        if (schoolSql.length() > 0) {
                            schoolSql.append(" OR ");
                        }
                        schoolSql.append(" FIND_IN_SET('").append(s).append("',track_detail.school_id_str) ");
                    }
                    q.or().apply(schoolSql.toString());
                });
            }
            if (yearClassIdStr != null && yearClassIdStr.length > 0) {
                String[] finalYearClassIdStr = yearClassIdStr;
                trackDetailQueryWrapper.and(q -> {
                    q.eq("track_detail.year_class_id_str", "").or().isNull("track_detail.year_class_id_str");
                    StringBuilder yearClassSql = new StringBuilder();
                    for (String s : finalYearClassIdStr) {
                        if (yearClassSql.length() > 0) {
                            yearClassSql.append(" OR ");
                        }
                        yearClassSql.append(" FIND_IN_SET('").append(s).append("',track_detail.year_class_id_str) ");
                    }
                    q.or().apply(yearClassSql.toString());
                });
            }
            if (classTypeIdStr != null && classTypeIdStr.length > 0) {
                String[] finalClassTypeIdStr = classTypeIdStr;
                trackDetailQueryWrapper.and(q -> {
                    q.eq("track_detail.class_type_id_str", "").or().isNull("track_detail.class_type_id_str");
                    StringBuilder classTypeSql = new StringBuilder();
                    for (String s : finalClassTypeIdStr) {
                        if (classTypeSql.length() > 0) {
                            classTypeSql.append(" OR ");
                        }
                        classTypeSql.append(" FIND_IN_SET('").append(s).append("',track_detail.class_type_id_str) ");
                    }
                    q.or().apply(classTypeSql.toString());
                });
            }
            trackDetailQueryWrapper.last("LIMIT 1");
//            trackDetailQueryWrapper.ne("track_detail.track_id",trackDetail.getId());
            TrackDetail detailServiceOne = null;

            //英语通关率不限制
            if (!trackMarketInfo.getClassify().equals(7)) {
                detailServiceOne = nITrackDetailService.detailServiceOne(trackDetailQueryWrapper);
            }

            if (detailServiceOne == null) {
                TrackDetail detail = new TrackDetail();
                detail.setTrackId(trackDetail.getId());
                detail.setType(type);
                detail.setSourseId(sourseId);
                detail.setClassify(trackMarketInfo.getClassify());
                detail.setTrackType(trackMarketInfo.getTrackType());
                detail.setGradeIdStr(trackDetail.getGradeIdStr());
                detail.setClassTypeIdStr(trackDetail.getClassTypeIdStr());
                detail.setSchoolIdStr(trackDetail.getSchoolIdStr());
                detail.setYearClassIdStr(trackDetail.getYearClassIdStr());

                Grade gradeServiceById = nIGradeService.getOne(new QueryWrapper<Grade>()
                        .eq("teacher_id", sourseId)
                        .eq("lesson_type", 1)
                        .eq("deleted", 0)
                        .eq("year_part", trackMarketInfo.getYearPart())
                        .eq("quarter_num", trackMarketInfo.getQuarterNum())
                        .last("limit 1"));
                if (gradeServiceById != null) {
                    Course course = iCourseService.getById(gradeServiceById.getCourseId());
                    if (course != null) {
                        detail.setSubjectsIdStr(course.getSubjectsId().toString());
                    }
                }
                nITrackDetailService.save(detail);
                iMqPushService.updateTrackDetail(detail);
            } else {
                trackDetailReturn = detailServiceOne;
            }
        }
        return trackDetailReturn;
    }
}
